#include "TcpServer.hpp"
#include <memory>

using namespace std;


void cal(const Request &req, Response &resp)
{
    resp.flag = 0;
    resp.result = 0;
    switch (req.op)
    {
    case '+':
        resp.result = req.x + req.y;
        break;
    case '-':
        resp.result = req.x - req.y;
        break;
    case '*':
        resp.result = req.x * req.y;
        break;
    case '/':
    {
        if (req.y == 0)
            resp.flag = DIV_ERR;
        else
            resp.result = req.x / req.y;
    }
    break;
    case '%':
    {
        if (req.y == 0)
            resp.flag = MOD_ERR;
        else
            resp.result = req.x % req.y;
    }
    break;
    default:
        resp.flag = OP_ERR;
        break;
    }
}

void Service(Connection *conn)
{
    std::string reqStr;
    while (getOnePackage(conn->inbuf, reqStr))  //读取一个完整的报文
    {
        std::string text;
        if(!deLength(reqStr, text)) return;     //提取有效载荷

        Request req;
        req.deserialize(&text);     //反序列化

        Response resp;
        cal(req,resp);      //计算结果

        string respStr;
        resp.serialize(&respStr);   //序列化

        conn->outbuf += enLength(respStr);  //添加协议报头
        //......
        std::cout<<"\n-----outbuf-------\n"<<conn->outbuf<<std::endl;
    }
    //直接发
    if(conn->_sender) conn->_sender(conn);
}

static void Usage(string str)
{
    cout << "Usage: " << str << " local_port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);
    unique_ptr<TcpServer> tcps(new TcpServer(port, Service));
    tcps->initServer();
    tcps->Dispatch();

    return 0;
}